package FD.Gestores;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class GestorDB {

    public static Connection getConexion() {

        Context ctx;
        Connection con = null;
        try {
            ctx = new InitialContext();
            DataSource ds;
            ds = (DataSource) ctx.lookup("jdbc/mysqltest");
            con = ds.getConnection();

        } catch (NamingException ex) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, ex);
        }


        return con;
    }

    public static boolean excuteCommand(String sql) {

        PreparedStatement sen = null;
        ResultSet rs = null;
        
        Connection conn = getConexion();

        try {

            sen = conn.prepareStatement(sql);
            sen.executeUpdate();

            if (rs.next()) {
                return true;
            } else {
                return false;
            }


        } catch (SQLException e) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, e);
            return false;
        } catch (Exception e) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, e);
            return false;
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static ArrayList excuteLoggin(String sql) {

        PreparedStatement sen = null;
        ResultSet rs = null;

        Connection conn = getConexion();
        ArrayList a = new ArrayList();
        try {

            sen = conn.prepareStatement(sql);
            sen.executeUpdate();

            if (rs.next()) {
                a.add(rs.getString(1));
                a.add(rs.getString(2));
                a.add(rs.getString(3));
            } 
        } catch (SQLException e) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, e);
        } catch (Exception e) {
            Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(GestorDB.class.getName()).log(Level.SEVERE, null, ex);
            }
            return a;
        }

    }
}
